﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CCWin;
using CCWin.SkinControl;
using CCWin.SkinClass;
using System.Runtime.InteropServices;
using System.Threading;
using GroupChat2013.Main.Properties;
using System.Diagnostics;
using CCWin.Win32;
using System.Xml;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text.RegularExpressions;
using GroupChat2013.Common;
using WebSocket4Net;
using GroupChat2013.Logic;
using GroupChat2013.Data;
using GroupChat2013.Entity;
using GroupChat2013.Service;
using GroupChat2013.Main.Components;
using GroupChat2013.Interface;
using GroupChat2013.Entity.Protocol;
using System.Runtime.Remoting.Messaging;
using System.Configuration;
using GroupChat2013.Main.Controls;
using GroupChat2013.Plugins;

namespace GroupChat2013.Main
{
    public partial class FrmLogin : CCSkinMain
    {
        #region 声明

        /// <summary>
        /// 消息盒子
        /// </summary>
        public FrmChatBox m_FrmChatBox = null;

        /// <summary>
        /// 主面板
        /// </summary>
        private FrmMain m_Frmmain = null;

        private FrmInformation m_FrmInformation;

        //private int headLeft;

        private WebSocket m_WebSocket;

        private List<RecLoginInfo> m_RecLoginList;

        private bool iconFlag = true;//用来标识图标闪动
        private Icon currIco;//当前正在闪动的图标

        /// <summary>
        /// 图标闪动定时器
        /// </summary>
        private System.Windows.Forms.Timer m_IconCounter;

        /// <summary>
        /// 是否已经登录
        /// </summary>
        private bool isLogin;

        /// <summary>
        /// 消息处理组件
        /// </summary>
        private List<IReceiveProcess> m_ReceiveProcess;

        /// <summary>
        /// 服务相关配置信息
        /// </summary>
        private ServcieConfig m_Config;

        /// <summary>
        /// 重新连接推送服务器
        /// </summary>
        private System.Windows.Forms.Timer reOpenPropelService = new System.Windows.Forms.Timer();

        #endregion

        #region 构造函数

        public FrmLogin()
        {
            InitializeComponent();

            SaveIntPtr();

            //headLeft = pnlTx.Left;

            reOpenPropelService.Interval = 8000;
            reOpenPropelService.Tick += new EventHandler(reOpenPropelService_Tick);

            this.Load += new EventHandler(FrmLogin_Load);
        }

        public FrmLogin(string message)
            : this()
        {
            RtxSignLogin();
        }

        #endregion

        #region Load事件

        /// <summary>
        /// 窗口加载时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmLogin_Load(object sender, EventArgs e)
        {
            int H = DateTime.Now.Hour;
            this.Back =
                H > 5 & H <= 11 ? Resources.morning :     //早上
                H > 11 & H <= 16 ? Resources.noon :       //中午
                H > 16 & H <= 19 ? Resources.afternoon :      //下午
                Resources.night;        //晚上

            m_FrmChatBox = new FrmChatBox();
            m_FrmChatBox.InitMessageBox();
            m_FrmChatBox.ResetHight();
            m_FrmChatBox.DoubleClickItemHandler += () =>
            {
                IconFlicker();
            };
            m_FrmChatBox.ReceiveNewUnReadMsgHandler += () =>
            {
                IconFlicker();
            };

            m_FrmInformation = new FrmInformation();

            #region 设置最近登录用户信息

            RecLoginRepository recLogin = new RecLoginRepository();
            m_RecLoginList = recLogin.GetRecLoginInfo(20);

            if (m_RecLoginList != null && m_RecLoginList.Count > 0)
            {
                RecLoginInfo rl = m_RecLoginList[0];
                txtId.SkinTxt.Text = rl.UserName;
                chkMima.Checked = rl.Rememberpw;
                chkZdLogin.Checked = rl.AutoLogin;
                txtPwd.SkinTxt.Text = rl.Password;

                if (rl.AutoLogin)
                {
                    btnDl_Click(btnDl, null);//直接登录
                }

                SetRecLogin(m_RecLoginList.FindAll(x => { return x.UserName != rl.UserName; }));
            }

            #endregion
        }

        /// <summary>
        /// 构建消息处理
        /// </summary>
        private void ReceiveProcessBuilder()
        {
            List<IReceiveProcess> processList = new List<IReceiveProcess>();

            //私聊消息处理
            processList.Add(new UserChatReceiveProcess(m_FrmChatBox));

            //群聊消息处理
            processList.Add(new GroupChatReceiveProcess(m_FrmChatBox, m_Frmmain));

            //更新群列表消息处理
            processList.Add(new GroupListReceiveProcess(m_Frmmain));

            //更新群相关信息消息处理
            processList.Add(new GroupChangeReceiveProcess());

            //更新群相关信息消息处理
            processList.Add(new PersonShareReceiveProcess(m_FrmInformation));

            //更新群相关信息消息处理
            processList.Add(new GroupShareReceiveProcess(m_FrmInformation));

            //更新用户在线状态处理
            processList.Add(new UserOnlineProcess(m_Frmmain));

            //更新用户离线状态处理
            processList.Add(new UserOfflineProcess(m_Frmmain));

            //获取未读消息处理
            processList.Add(new UnReadMesageProcess(m_Frmmain, m_FrmInformation));

            m_ReceiveProcess = processList;
        }

        private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.tuopan.Visible = false;
        }

        /// <summary>
        /// 设置最近登录
        /// </summary>
        private void SetRecLogin(List<RecLoginInfo> recLoginList)
        {
            MenuId.Items.Clear();
            MenuId.Height = 4;
            recLoginList.ForEach(x =>
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.AutoSize = false;
                item.Size = new System.Drawing.Size(182, 45);
                item.Text = x.UserName;
                item.Image = Image.FromFile(GroupChat2013.Common.Helper.CombinePath(@"head\1.png"));
                item.Click += (s, e) =>
                {
                    txtId.SkinTxt.Text = x.UserName;
                    if (x.Rememberpw)
                    {
                        txtPwd.SkinTxt.Text = x.Password;
                    }
                    chkMima.Checked = x.Rememberpw;
                    chkZdLogin.Checked = x.AutoLogin;

                    pnlImgTx.BackgroundImage = item.Image;
                    SetRecLogin(m_RecLoginList.FindAll(y => { return y.UserName != x.UserName; }));
                };

                MenuId.Height += 45;
                MenuId.Items.Add(item);
            });
        }

        #endregion

        #region 登录事件

        //private Thread LoginThread;

        /// <summary>
        /// 登录事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>        
        private void btnDl_Click(object sender, EventArgs e)
        {
            if (txtId.SkinTxt.Text.Length == 0 || txtPwd.SkinTxt.Text.Length == 0)
            {
                return;
            }

            #region 检测服务器配置

            ParseConfig<ServcieConfig> parseConfig = FrmServiceConfig.GetServcieConfig();

            m_Config = parseConfig.Parse();
            if (string.IsNullOrEmpty(m_Config.PropelConfig.IP) || string.IsNullOrEmpty(m_Config.BusinessConfig.IP))
            {
                if (MessageBoxEx.Show("请先配置服务器相关信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information) ==
                     System.Windows.Forms.DialogResult.OK)
                {
                    FrmServiceConfig frmConfig = new FrmServiceConfig(parseConfig);
                    frmConfig.TopMost = true;

                    if (frmConfig.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                        this.Close();
                }
                else
                {
                    return;
                }
            }

            #endregion

            ServiceUrlProxy.GetInstance().SetBaseUrl(m_Config.BusinessConfig.IP, m_Config.BusinessConfig.Port);

            imgLoadding.Visible = true;
            //登录后控件相关处理
            txtId.Enabled = txtPwd.Enabled =
                btnId.Enabled = chkMima.Enabled = chkZdLogin.Enabled = false;
            btnDl.Visible = false;
            btnCancel.Visible = true;
            //头像局中
            //pnlTx.Left = (this.Width - pnlTx.Width) / 2;

            AsyncClient.AsyncCall<LoginValueInfo>(() =>
                {
                    string rootdeptId = ConfigurationManager.AppSettings["rootdeptId"];
                    return ServiceUrlProxy.GetInstance().UserLogin(rootdeptId, txtId.SkinTxt.Text, txtPwd.SkinTxt.Text);
                },
                (value) =>
                {
                    if (value == null)
                    {
                        this.BeginInvoke(new MethodInvoker(() =>
                        {
                            MessageBoxEx.Show("服务器连接异常，或账号密码错误", "登录失败",
                             MessageBoxButtons.OK, MessageBoxIcon.Error);
                            ResetView();
                        }));
                        return;
                    }
                    else if (string.IsNullOrEmpty(value.userInfoId))
                    {
                        this.BeginInvoke(new MethodInvoker(() =>
                        {
                            MessageBoxEx.Show("您输入的帐号或密码错误", "登录失败",
                             MessageBoxButtons.OK, MessageBoxIcon.Error);
                            ResetView();
                        }));
                        return;
                    }
                    else
                    {
                        //初始化引擎
                        EngineContext.Initialize(false);

                        //设置当前用户
                        EngineContext.Current.CurrUserInfo = new UserInfo()
                        {
                            UserId = value.userInfoId,
                            UserName = value.loginName,
                            Name = value.loginName,
                            CID = value.regCode,
                            groupAdmin=value.groupAdmin
                        };

                        //初始化并打开WebSocket
                        OpenWebSocket();
                    }
                });
        }

        /// <summary>
        /// 从RTX激活并使用签名登陆
        /// </summary>
        private void RtxSignLogin()
        {
            chkMima.Checked = false;
            chkZdLogin.Checked = false;
            chkMima.Checked = false;

            RtxSignInfo signInfo = GroupChat2013.Common.Helper.GetRTXSign();
            if (signInfo == null)
            {
                MessageBoxEx.Show("获取RTX签名失败", "获取签名失败",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);

                this.Close();
                return;
            }

            txtId.SkinTxt.Text = signInfo.Account;
            txtPwd.SkinTxt.Text = signInfo.Sign;

            #region 检测服务器配置

            ParseConfig<ServcieConfig> parseConfig = FrmServiceConfig.GetServcieConfig();

            m_Config = parseConfig.Parse();
            if (string.IsNullOrEmpty(m_Config.PropelConfig.IP) || string.IsNullOrEmpty(m_Config.BusinessConfig.IP))
            {
                if (MessageBoxEx.Show("请先配置服务器相关信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information) ==
                     System.Windows.Forms.DialogResult.OK)
                {
                    FrmServiceConfig frmConfig = new FrmServiceConfig(parseConfig);
                    frmConfig.TopMost = true;

                    if (frmConfig.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                        this.Close();
                }
                else
                {
                    return;
                }
            }

            #endregion

            ServiceUrlProxy.GetInstance().SetBaseUrl(m_Config.BusinessConfig.IP, m_Config.BusinessConfig.Port);

            imgLoadding.Visible = true;
            //登录后控件相关处理
            txtId.Enabled = txtPwd.Enabled =
                btnId.Enabled = chkMima.Enabled = chkZdLogin.Enabled = false;
            btnDl.Visible = false;
            btnCancel.Visible = true;
            //头像局中
            //pnlTx.Left = (this.Width - pnlTx.Width) / 2;

            AsyncClient.AsyncCall<LoginValueInfo>(() =>
                {
                    string rootdeptId = ConfigurationManager.AppSettings["rootdeptId"];
                    return ServiceUrlProxy.GetInstance().UserRtxSign(rootdeptId, signInfo.Account, signInfo.Sign);
                },
                (value) =>
                {
                    if (value == null || string.IsNullOrEmpty(value.userInfoId))
                    {
                        this.BeginInvoke(new MethodInvoker(() =>
                        {
                            MessageBoxEx.Show("RTX签名登陆失败", "登录失败",
                             MessageBoxButtons.OK, MessageBoxIcon.Error);

                            ResetView();

                            txtPwd.SkinTxt.Text = string.Empty;
                            chkMima.Checked = false;
                        }));
                        return;
                    }
                    else
                    {
                        //初始化引擎
                        EngineContext.Initialize(false);

                        //设置当前用户
                        EngineContext.Current.CurrUserInfo = new UserInfo()
                        {
                            UserId = value.userInfoId,
                            UserName = value.loginName,
                            Name = value.loginName,
                            CID = value.regCode
                        };

                        //初始化并打开WebSocket
                        OpenWebSocket();
                    }
                });
        }

        /// <summary>
        /// 初始化并打开WebSocket
        /// </summary>
        private void OpenWebSocket()
        {
            m_WebSocket = null;
            //m_WebSocket = new WebSocket("ws://" + m_Config.PropelConfig.IP + ":" + m_Config.PropelConfig.Port + "/websocket/" + EngineContext.Current.CurrUserInfo.UserId, WebSocketVersion.Rfc6455);

            string ipPort = m_Config.PropelConfig.IP + ":" + m_Config.PropelConfig.Port;

            m_WebSocket = new WebSocket("ws://" + ipPort + "/websocket/" + EngineContext.Current.CurrUserInfo.UserId, "", null, null, "UserAgent", "http://" + ipPort, WebSocketVersion.Rfc6455);

            m_WebSocket.Opened += new EventHandler(websocket_Opened);
            m_WebSocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error);
            m_WebSocket.Closed += new EventHandler(websocket_Closed);
            m_WebSocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);
            m_WebSocket.Open();
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                //if (LoginThread != null)
                //{
                //    LoginThread.Abort();
                //}

                ResetView();
                m_WebSocket.Close();
            }
            catch { }
        }

        private void ResetView()
        {
            imgLoadding.Visible = false;
            //登录后控件相关处理
            txtId.Enabled = txtPwd.Enabled =
                btnId.Enabled = chkMima.Enabled = chkZdLogin.Enabled = true;
            btnDl.Visible = true;
            btnCancel.Visible = false;
            //头像局中
            //pnlTx.Left = headLeft;
        }

        #endregion

        #region 重连WebSocket

        private void reOpenPropelService_Tick(object sender, EventArgs e)
        {
            tuopan.BalloonTipText = "与推送服务器断开，正在尝试重新连接.";
            tuopan.BalloonTipTitle = "连接推送服务";
            tuopan.ShowBalloonTip(0);

            OpenWebSocket();
            reOpenPropelService.Enabled = false;
            reOpenPropelService.Stop();
        }

        #endregion

        #region WebSocket Event

        private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            TransferMsgInfo msg = JsonConvert.Parse<TransferMsgInfo>(e.Message);
            if (msg == null)
                return;

            this.BeginInvoke(new MethodInvoker(() =>
            {
                //消息处理
                m_ReceiveProcess.ForEach(x =>
                {
                    if (x.Process(msg))
                        return;
                });
            }));
        }

        private void websocket_Closed(object sender, EventArgs e)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                //如果是在主面板
                if (m_Frmmain != null)
                {
                    reOpenPropelService.Enabled = true;
                    reOpenPropelService.Start();
                }
            }));
        }

        private void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
        {
            LogHelper.LogError("websocket_Error:" + e.Exception.Message);

            this.Invoke(new MethodInvoker(() =>
            {
                //如果是在登录界面
                if (m_Frmmain == null)
                {
                    ResetView();

                    MessageBoxEx.Show("服务器连接异常", "WebSocket连接提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else //如果是在主面板
                {
                    reOpenPropelService.Enabled = true;
                    reOpenPropelService.Start();
                }
            }));
        }

        private void websocket_Opened(object sender, EventArgs e)
        {
            if (btnDl.Visible)
            {
                m_WebSocket.Close();
                return;
            }

            TabConfigInfo tabConfigInfo = ServiceUrlProxy.GetInstance().GetTabConfig();
            if (tabConfigInfo == null)
                tabConfigInfo.showTab = ConstClass.SimpleRTXPlugin;

            MainButtonConfigParse buttonConfigParse = new MainButtonConfigParse();
            List<ButtonConfigInfo> buttonConfigList = buttonConfigParse.Parse();

            this.Invoke(new MethodInvoker(() =>
               {
                   //如果是在登录界面
                   if (this.Visible)
                   {
                       LoginSucc();

                       if (m_Frmmain == null)
                       {
                           m_Frmmain = new FrmMain();
                           m_Frmmain.CompletedHandle += () =>
                           {
                               this.Visible = false;
                               isLogin = true;

                               //初始化tab
                               m_Frmmain.InitMainTab(tabConfigInfo);

                               //初始化主面板按钮
                               m_Frmmain.InitMainButton(buttonConfigList);

                               //初始化托盘图标闪烁
                               InitIconCounter();

                               ReceiveProcessBuilder();

                               EngineContext.Current.ChatConfig = new ParseConfig<ChatConfigInfo>(
                                   EngineContext.Current.FilePathManager.PersonConfigPath,
                                 ConstClass.ChatConfigName, () => ChatPanel.GetDefault());

                               this.tuopan.DoubleClick += new System.EventHandler(this.tuopan_DoubleClick);
                               this.tuopan.MouseMove += new System.Windows.Forms.MouseEventHandler(this.tuopan_MouseMove);
                           };

                           m_Frmmain.ExistedHandle += () =>
                           {
                               tuopan.Visible = false;
                               tuopan.Icon = null;

                               m_WebSocket.Close();
                           };
                       }
                       m_Frmmain.Show();
                   }
                   else //如果是在主面板
                   {

                   }
               }));

            m_WebSocket.Send("登陆成功");
        }

        /// <summary>
        /// 登录成功后
        /// </summary>
        private void LoginSucc()
        {
            RecLoginRepository recLogin = new RecLoginRepository();
            //保存登录记录
            recLogin.AddRecLoginInfo(new RecLoginInfo()
            {
                UserId = Guid.NewGuid().ToString("N"),
                UserName = txtId.SkinTxt.Text,

                AutoLogin = chkZdLogin.Checked,
                Rememberpw = chkMima.Checked,

                Password = chkMima.Checked ? txtPwd.SkinTxt.Text : string.Empty
            });
        }

        #endregion

        #region 托盘闪烁等方法

        private void InitIconCounter()
        {
            m_IconCounter = new System.Windows.Forms.Timer();
            m_IconCounter.Interval = 450;
            m_IconCounter.Tick += (s, e) =>
            {
                if (iconFlag)  //当该值为真时
                {
                    tuopan.Icon = currIco;//设定托盘控件taskBarIcon的图标
                    iconFlag = false;                       //修改该值为假
                }
                else                                            //当该值为假时
                {
                    tuopan.Icon = Properties.Resources.empty; //设定托盘控件taskBarIcon的图标
                    iconFlag = true;                             //修改该值为真
                }
            };
        }

        /// <summary>
        /// 重设图标闪动状态
        /// </summary>
        /// <returns></returns>
        private ChatMessageSubItem ResetIconFlicker()
        {
            ChatMessageSubItem baseValue = m_FrmChatBox.RemoveAt(0);
            IconFlicker();
            return baseValue;
        }

        /// <summary>
        /// 双击消息闪动图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void tuopan_DoubleClick(object sender, EventArgs e)
        {
            if (m_Frmmain == null)
            {
                this.Show();
                return;
            }

            if (m_FrmChatBox.NotifyItemCount == 0)
            {
                m_Frmmain.Show();
                return;
            }

            ChatMessageSubItem chatItem = ResetIconFlicker();
            tuopan_MouseMove(tuopan, null);

            if (chatItem.ChatType == ChatType.User)
            {
                FrmChatBox.ShowFrmChat(chatItem);
            }
            else if (chatItem.ChatType == ChatType.Group)
            {
                FrmChatBox.ShowFrmGroup(chatItem);
            }
        }

        private List<string> getDicKeys(Dictionary<string, FrmChat>.KeyCollection keys)
        {
            List<string> result = new List<string>();
            foreach (string key in keys)
            {
                result.Add(key);
            }

            return result;
        }

        /// <summary>
        /// 提示栏图片闪动
        /// </summary>
        private void IconFlicker()
        {
            if (m_FrmChatBox.NotifyItemCount == 0)
            {
                m_IconCounter.Stop();
                tuopan.Icon = Properties.Resources.win_icon_16;
                return;
            }

            currIco = m_FrmChatBox[0].ChatType == ChatType.Group ?
                              Properties.Resources.group : Properties.Resources.user;

            m_IconCounter.Start();
        }

        #endregion

        #region 窗体相关事件

        /// <summary>
        /// 用户名编辑事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtId_SkinTxt_TextChanged(object sender, EventArgs e)
        {
            if (m_RecLoginList != null)
            {
                RecLoginInfo recLogin = m_RecLoginList.Find(x => { return x.UserName == txtId.SkinTxt.Text; });
                txtPwd.SkinTxt.Text = recLogin == null ? string.Empty : recLogin.Password;
            }
        }

        /// <summary>
        /// 悬浮时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Control_MouseEnter(object sender, EventArgs e)
        {
            txtId.MouseState = ControlState.Hover;
        }

        /// <summary>
        /// 离开时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Control_MouseLeave(object sender, EventArgs e)
        {
            txtId.MouseState = ControlState.Normal;
        }

        /// <summary>
        /// 账号下拉框按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnId_MouseDown(object sender, MouseEventArgs e)
        {
            if (MenuId.Items.Count > 0)
            {
                MenuId.Show(txtId, 1, txtId.Height + 1);
                btnId.StopState = StopStates.Pressed;
                btnId.Enabled = false;
                txtId.MouseState = ControlState.Hover;
            }
        }

        /// <summary>
        /// 账号下拉菜单关闭时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuId_Closing(object sender, ToolStripDropDownClosingEventArgs e)
        {
            btnId.Enabled = true;
            btnId.StopState = StopStates.NoStop;
            btnId.ControlState = txtId.MouseState = ControlState.Normal;
        }

        /// <summary>
        /// 软键盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPwd_IconClick(object sender, EventArgs e)
        {
            PassKey pass = new PassKey(this.Left + txtPwd.Left - 25, this.Top + txtPwd.Bottom, txtPwd.SkinTxt);
            pass.Show(this);
        }

        /// <summary>
        /// 自动登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkZdLogin_CheckedChanged(object sender, EventArgs e)
        {
            chkMima.Checked = chkZdLogin.Checked ? true : chkMima.Checked;
        }

        /// <summary>
        /// 记住密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkMima_CheckedChanged(object sender, EventArgs e)
        {
            if (!chkMima.Checked && chkZdLogin.Checked)
            {
                chkZdLogin.Checked = false;
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 显示控制面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolQQShow_Click(object sender, EventArgs e)
        {
            if (m_Frmmain == null)
            {
                this.Show();
            }
            else
            {
                m_Frmmain.Show();
            }
        }

        string newLine = Environment.NewLine;
        private void btnMbShow_Click(object sender, EventArgs e)
        {
            string info = "简单文字信息................" + newLine +
             "简单文字信息................";
            MessageBoxEx.Show(info);
            MessageBoxEx.Show(info, "带标题的示例");
            MessageBoxEx.Show(info, "带标题的示例",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
            MessageBoxEx.Show(info, "带标题的示例",
                MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            MessageBoxEx.Show(info, "带标题的示例",
                MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
            MessageBoxEx.Show(info, "带标题的示例",
                MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            MessageBoxEx.Show(info, "带标题的示例",
                MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
            MessageBoxEx.Show(info, "带标题的示例",
                MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
        }

        int mouseX = 0;

        /// <summary>
        /// 鼠标移动到托盘程序显示消息盒子
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tuopan_MouseMove(object sender, MouseEventArgs e)
        {
            if (isLogin &&
                !QQMenu.Visible)
            {
                Point pt = new Point();
                WinApi.GetCursorPos(out pt);
                if (mouseX == 0 || Math.Abs(pt.X - mouseX) > 30)
                {
                    mouseX = pt.X;
                }

                int x = mouseX - this.m_FrmChatBox.Width / 2;

                //如果消息盒子右边距超出了屏幕，则重新计算
                if (Screen.PrimaryScreen.WorkingArea.Width <= x + this.m_FrmChatBox.Width)
                    x = Screen.PrimaryScreen.WorkingArea.Width - this.m_FrmChatBox.Width - 3;

                int y = Screen.PrimaryScreen.WorkingArea.Height - this.m_FrmChatBox.Height;
                this.m_FrmChatBox.Show(x, y - 2);
            }
            else
            {
                this.m_FrmChatBox.Hide();
            }
        }

        public new void Show()
        {
            if (m_Frmmain != null && !m_Frmmain.IsDisposed)
            {
                m_Frmmain.Show();
            }
            else
            {
                base.Show();
                this.WindowState = FormWindowState.Normal;
                WinAPI.SetActiveWindow(this.Handle);
            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void SaveIntPtr()
        {
            string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstClass.DataDirName);
            if (!File.Exists(configPath))
                Tools.CreateDir(configPath);

            string CurrentIntPtr = Path.Combine(configPath, ConstClass.CurrentIntPtr);
            FileStream fs = File.Open(CurrentIntPtr, FileMode.Create, FileAccess.Write);
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.WriteLine((Int64)this.Handle);
            }
            fs.Close();
        }

        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case WinApi.WM_COPYDATA:
                    COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                    Type mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    string content = mystr.lpData;
                    DispatcherMethed(content);
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        public void DispatcherMethed(string message)
        {
            this.BeginInvoke(new Action(() =>
            {
                switch (message)
                {
                    case "Show":
                        this.Show();
                        break;
                    case "1"://从RTX客户端激活
                        RtxSignLogin();
                        break;
                    case "0"://从RTX客户端退出
                        if (MessageBoxEx.Show("是否从RTX端关闭？", "提示",
                          MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                            Application.Exit();
                        break;
                }
            }));
        }

        #endregion

        /// <summary>
        /// 系统按钮 打开服务地址配置
        /// </summary>
        /// <param name="sender"></param>
        private void FrmLogin_SysBottomClick(object sender)
        {
            ParseConfig<ServcieConfig> parseConfig = FrmServiceConfig.GetServcieConfig();
            FrmServiceConfig frmConfig = new FrmServiceConfig(parseConfig);
            frmConfig.TopMost = true;
            frmConfig.ShowDialog();
        }
    }
}